// 数据渲染
$(function () {
  let id = location.search.split("=")[1];
  $.ajax({
    url: "../../interface/getitem.php",
    type: "get",
    data: { id },
    dataType: "json",
  })
    .then((res) => {
      let pic = JSON.parse(res.picture);

      let template = "";

      $(".title").html(res.title);
      $(".price").html(res.price);

      pic.forEach((el, i) => {
        i = 0 ? null : (template += `<img src="../${el.src}" alt="" />`);
      });

      $(".img-wp div").html(template);
      // 事件添加
      //--------------------------
      $(".btn").on("click", function () {
        addItem(res.ID, $("#num").val());
      });
    })
    .catch((xhr) => {});
});

function addItem(id, num) {
  let product = { id, num };

  let shop = cookie.get("shop");
  if (shop) {
    shop = JSON.parse(shop);

    if (shop.some((el) => el.ID == id)) {
      let index = shop.findIndex((elm) => elm.ID == id);
      let count = parseInt(shop[index].num);
      count += parseInt(num);
      shop[index].num = count;
    } else {
      shop.push(product);
    }
  } else {
    shop = [];
    shop.push(product);
  }

  cookie.set("shop", JSON.stringify(shop));
}
